package com.info.filter;

import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.regex.Pattern;

@WebFilter(filterName = "LoginSessionFilter",urlPatterns="/user/*",initParams = {@WebInitParam(name="sessionKey",value = "UserSession"),
        @WebInitParam(name="redirectUrl",value = "/login.jsp"),@WebInitParam(name="excepUrlRegex",value = "/loginServlet")})
public class LoginSessionFilter implements Filter {

    // 初始化
    // 检查session名称
    private String sessionKey;

    // 需要排除（不拦截）的URL的地址，使用正则表达式
    private Pattern excepUrlPattern;

    // 检查不通过时，转发的URL
    private String forwardUrl;

    // 重定向的URL
    private String redirectUrl;

    @Override
    public void init(FilterConfig cfg) throws ServletException {
        sessionKey = cfg.getInitParameter("sessionKey");

        String excepUrlRegex = cfg.getInitParameter("excepUrlRegex");

        if (!StringUtils.isBlank(excepUrlRegex)) {
            excepUrlPattern = Pattern.compile(excepUrlRegex);
        }

        forwardUrl = cfg.getInitParameter("forwardUrl");

        redirectUrl = cfg.getInitParameter("redirectUrl");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 如果为设置的sessionKey的值为空，则直接放行
        if (StringUtils.isBlank(sessionKey)) {
            chain.doFilter(request, response);
            return;
        }

        // 不为空已经定义
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String servletPath = req.getServletPath();

        // 如果请求的路径与forwardUrl相同，或请求的路径是排除的URL时，则直接放行
        if (servletPath.equals(forwardUrl)
                || excepUrlPattern.matcher(servletPath).matches()) {

            chain.doFilter(request, response);
            return;
        }

        Object sessionObj = req.getSession().getAttribute(sessionKey);
        // 如果session为空，则跳转到指定页面
        if (sessionObj == null) {
            String contextPath = req.getContextPath();
            //redirect是上一个页面的请求地址，也就是过滤后，如果是请求需要登录验证的页面，且未登录，则服务器端向客户端
            //发送重定向跳转
            String redirect = servletPath+"?"+StringUtils.defaultString(req.getQueryString());
            //req.getQueryString()取的地址是?后面的地址字符串

            //如果forwardUrl为空，则返回redirectUrl。否则返回forwardUrl
            //这里面contextPath的地址是http://localhost:8080/项目名称/
            //StringUtils.defaultIfEmpty(forwardUrl, redirectUrl)得到的地址是login.jsp
            resp.sendRedirect(contextPath+StringUtils.defaultIfEmpty(forwardUrl, redirectUrl)+"?redirect="+ URLEncoder.encode(redirect,"UTF-8"));
        }else
        {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
